#include <fstream>
#include <cmath>
#include <iostream>
using namespace std;
float cos1(float);
float sin1(float angle)
{
    return cos1(angle - 90);
}

float cos1(float angle)
{
    const int precision = 10000; // 保存到0.0001
    const int cacheSize = 90 * precision;
    static float cosCache[cacheSize] = {0};

    if (cosCache[0] == 0) // 加载数据
    {
        static bool loading = false; // 若短时间内再次访问，则不再开启线程进行加载
        const double pi = 3.1415926535898;
        if (!loading)
        {
            loading = true;

            fstream file("/home/xxuffei/cos9.dat", std::ios_base::in|std::ios_base::binary);
            if (file)
            {
                file.read((char*)cosCache, sizeof(cosCache));
                file.close();
            }
            else
            {
                file.close();
                for (int i = 0; i < cacheSize; ++i)
                {
                    cosCache[i] = static_cast<float>(std::cos(i * (pi / 180 / precision)));
                }
                file.open("/home/xxuffei/cos9.dat", std::ios_base::out|std::ios_base::binary);
                file.write((char*)cosCache, sizeof(cosCache));
                file.close();
            }

        }
        return std::cos(angle * (pi / 180)); // 在加载的同时直接返回值，不进行等待
    }

    int angleIndex = int(round(abs(angle) * precision)) % (360*precision);
    switch (angleIndex / cacheSize) {
    case 0:
        return cosCache[angleIndex];
    case 1:
        angleIndex -= cacheSize;
        if (90*precision == cacheSize - angleIndex)
            return 0;
        return -cosCache[cacheSize - angleIndex];
    case 2:
        return -cosCache[angleIndex % cacheSize];
    case 3:
        angleIndex %= cacheSize;
        if (90*precision == cacheSize - angleIndex)
            return 0;
        return cosCache[cacheSize - angleIndex];
    default:
        return 0;
    }
}
int main(){
    cout<<cos1(1.3)<<endl;
    return 0;
}
